package com.snail.clouds.api.controller;

import com.snail.clouds.framework.api.ApiResponse;
import com.snail.clouds.framework.dto.UserLoginDTO;
import com.snail.clouds.framework.dto.UserLoginResponseDTO;
import com.snail.clouds.framework.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    @Autowired
    private AuthService authService;
    
    /**
     * 用户登录
     * @param loginDTO 登录信息
     * @return 登录响应
     */
    @PostMapping("/login")
    public ApiResponse<UserLoginResponseDTO> login(@Valid @RequestBody UserLoginDTO loginDTO) {
        try {
            UserLoginResponseDTO response = authService.login(loginDTO);
            return ApiResponse.success("登录成功", response);
        } catch (Exception e) {
            log.error("用户登录失败: {}", e.getMessage());
            return ApiResponse.error("登录失败: " + e.getMessage());
        }
    }
    
    /**
     * 刷新Token
     * @param token 原始Token
     * @return 新的Token
     */
    @PostMapping("/refresh")
    public ApiResponse<String> refreshToken(@RequestHeader("Authorization") String token) {
        try {
            // 去掉Bearer前缀
            String jwtToken = token.replace("Bearer ", "");
            String newToken = authService.refreshToken(jwtToken);
            if (newToken != null) {
                return ApiResponse.success("Token刷新成功", newToken);
            } else {
                return ApiResponse.error("Token刷新失败");
            }
        } catch (Exception e) {
            log.error("Token刷新失败: {}", e.getMessage());
            return ApiResponse.error("Token刷新失败: " + e.getMessage());
        }
    }
    
    /**
     * 验证Token
     * @param token JWT Token
     * @return 是否有效
     */
    @PostMapping("/validate")
    public ApiResponse<Boolean> validateToken(@RequestHeader("Authorization") String token) {
        try {
            // 去掉Bearer前缀
            String jwtToken = token.replace("Bearer ", "");
            boolean isValid = authService.validateToken(jwtToken);
            return ApiResponse.success("Token验证成功", isValid);
        } catch (Exception e) {
            log.error("Token验证失败: {}", e.getMessage());
            return ApiResponse.<Boolean>error("Token验证失败: " + e.getMessage());
        }
    }
}